<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>信息流管理</el-breadcrumb-item>
      <el-breadcrumb-item>
        <span
          class="u-cursor"
          @click="$router.back()"
        >客户管理</span>
      </el-breadcrumb-item>
      <el-breadcrumb-item>{{pageTitle}}客户信息</el-breadcrumb-item>
    </el-breadcrumb>
    <Container class="u-pb60">
      <el-form
        class="m-form--detail"
        label-width="160px"
        :model="pageData"
        :rules="pageRules"
        ref="pageForm"
      >
        <ContainerTitle>基本信息</ContainerTitle>
        <el-form-item
          required
          prop="customerName"
          size="small"
          label="客户全称："
        >
          <el-autocomplete
            class="u-w350"
            clearable
            v-model.trim="pageData.customerName"
            :disabled="pageAction === 'detail'"
            :fetch-suggestions="customerQuerySearch"
            placeholder="请输入客户全称"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item
          required
          prop="customerType"
          label="客户性质："
        >
          <el-radio-group
            :disabled="pageAction === 'detail'"
            v-model="pageData.customerType"
          >
            <el-radio
              v-for="item in CUSTOMER_TYPE_OPTION"
              :key="item.value"
              :label="item.value"
            >{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          required
          prop="customerRole"
          label="客户角色："
        >
          <el-radio-group
            :disabled="pageAction === 'detail'"
            v-model="pageData.customerRole"
          >
            <el-radio
              v-for="item in CUSTOMER_ROLE_OPTION"
              :key="item.value"
              :label="item.value"
            >{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="客户联系方式：">
          <el-row
            class="u-mb20"
            v-if="['create', 'edit'].includes(pageAction) && !pageData.customerContact.length"
          >
            <el-button
              size="small"
              type="primary"
              @click="addCustomerContact"
            >添加</el-button>
          </el-row>
          <el-row
            v-for="(item, index) in pageData.customerContact"
            :key="index"
            class="u-mb20"
          >
            <el-form-item
              class="u-mb20"
              label="负责人"
              label-width="80px"
              :prop="'customerContact.' + index + '.principal'"
              :rules="customerContactRules.principal"
            >
              <el-input
                class="u-w270"
                size="small"
                placeholder="请输入负责人"
                v-model.trim="item.principal"
                :disabled="pageAction === 'detail'"
              ></el-input>
              <el-button
                v-if="['create', 'edit'].includes(pageAction)"
                size="small"
                class="u-ml10"
                type="primary"
                @click="addCustomerContact"
              >添加</el-button>
              <el-button
                size="small"
                class="u-ml10"
                v-if="['create', 'edit'].includes(pageAction)"
                @click="removeCustomerContact(index)"
              >删除</el-button>
            </el-form-item>
            <el-form-item
              class="u-mb20"
              label="联系方式"
              label-width="80px"
              :prop="'customerContact.' + index + '.contact'"
              :rules="customerContactRules.contact"
            >
              <el-input
                class="u-w270"
                size="small"
                placeholder="请输入联系方式"
                v-model.trim="item.contact"
                :disabled="pageAction === 'detail'"
              ></el-input>
            </el-form-item>
            <el-form-item
              class="u-mb20"
              label="联系地址"
              label-width="80px"
              :prop="'customerContact.' + index + '.address'"
              :rules="customerContactRules.address"
            >
              <el-input
                type="textarea"
                class="u-w270"
                size="small"
                placeholder="请输入联系地址"
                v-model.trim="item.address"
                :disabled="pageAction === 'detail'"
              ></el-input>
            </el-form-item>
          </el-row>
        </el-form-item>

        <template v-if="pageAction === 'detail'">
          <el-form-item label="客户状态：">{{mapOptionLabel(CUSTOMER_STATUS_OPTION, pageData.status)}}</el-form-item>
          <el-form-item label="关联资质：">
            <el-button
              v-if="pageData.aptitudeCount > 0"
              size="small"
              type="text"
              @click="$router.push({
                name: 'flow-customer-aptitude',
                query: {
                  id: $route.query.id
                }
              })"
            >{{pageData.aptitudeCount}}</el-button>
            <template v-else>{{pageData.aptitudeCount}}</template>
          </el-form-item>
          <el-form-item label="最后操作人：">{{pageData.updateBy}}</el-form-item>
          <el-form-item label="最后操作时间：">{{pageData.updateTime}}</el-form-item>
        </template>
      </el-form>
    </Container>
    <Affix :offset-bottom="0">
      <ButtonGroup
        isFixed
        align="right"
      >
        <el-button
          size="small"
          @click="$router.back()"
        >返回</el-button>
        <el-button
          size="small"
          type="primary"
          v-if="['create', 'edit'].includes(pageAction)"
          @click="handleEnsure"
        >确定</el-button>
      </ButtonGroup>
    </Affix>
  </div>
</template>

<script>
import ContainerTitle from "@/components/container-title";
import Container from "@/components/container";
import Affix from "@/components/affix";
import ButtonGroup from "@/components/button-group";

import {
  CUSTOMER_TYPE_OPTION,
  CUSTOMER_ROLE_OPTION,
  CUSTOMER_STATUS_OPTION
} from "@/assets/js/flow-option";
import { getStrLen, mapOptionLabel } from "@/util";

export default {
  components: {
    ContainerTitle,
    Container,
    Affix,
    ButtonGroup
  },
  data() {
    return {
      CUSTOMER_TYPE_OPTION,
      CUSTOMER_ROLE_OPTION,
      CUSTOMER_STATUS_OPTION,

      pageAction: this.$route.query.action,

      customerOptions: [],

      pageData: {
        customerName: "",
        customerType: 1,
        customerRole: 1,
        customerContact: []
      },
      pageRules: {
        customerName: {
          required: true,
          validator: (rule, value, callback) => {
            if (!value || value.trim() === "") {
              callback(new Error("请输入客户全称"));
            } else if (getStrLen(value) > 50) {
              callback(new Error("客户名称最多50个字符"));
            } else {
              callback();
            }
          },
          trigger: ["change", "blur"]
        },
        customerType: {
          required: true,
          message: "请选择客户性质",
          trigger: ["change", "blur"]
        },
        customerRole: {
          required: true,
          message: "请选择客户角色",
          trigger: ["change", "blur"]
        }
      },

      // 联系方式
      customerContactRules: {
        principal: {
          required: true,
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error("请输入负责人"));
            } else if (getStrLen(value) > 20) {
              callback(new Error("负责人最多20个字符"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        contact: {
          required: true,
          message: "请输入联系方式",
          trigger: ["blur", "change"]
        },
        address: {
          required: true,
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error("请输入联系地址"));
            } else if (getStrLen(value) > 50) {
              callback(new Error("联系地址最多50个字符"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        }
      }
    };
  },
  computed: {
    pageTitle() {
      return {
        create: "新增",
        edit: "编辑",
        detail: "查看"
      }[this.pageAction];
    }
  },
  methods: {
    mapOptionLabel,

    // 客户名称搜索
    customerQuerySearch(queryString, cb) {
      let results = queryString
        ? this.customerOptions.filter(this.customerQueryFilter(queryString))
        : this.customerOptions;
      cb(results);
    },
    customerQueryFilter(queryString) {
      return restaurant => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    fetchCustomerOptions() {
      this.$http({
        method: "get",
        url: "/manage/api/bus/customer/get_customer_name",
        params: {
          status: 0
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.customerOptions = res.data.data.map(item => {
            return {
              ...item,
              value: item.name
            };
          });
        }
      });
    },
    // 确定
    handleEnsure() {
      if (this.pageAction === "edit") {
        this.updateDetail();
      } else {
        this.createDetail();
      }
    },
    // 新建
    createDetail() {
      this.$refs.pageForm.validate(valid => {
        if (valid) {
          this.$http({
            method: "post",
            url: "/manage/api/bus/customer/add",
            data: this.pageData
          }).then(res => {
            if (res.data.code === 0) {
              this.$message.success("新建成功！");
              this.$router.back();
            } else {
              this.$message.error(res.data.msg);
            }
          });
        }
      });
    },
    // 编辑
    updateDetail() {
      this.$refs.pageForm.validate(valid => {
        if (valid) {
          this.$http({
            method: "post",
            url: "/manage/api/bus/customer/update",
            data: this.pageData
          }).then(res => {
            if (res.data.code === 0) {
              this.$message.success("修改成功！");
              this.$router.back();
            } else {
              this.$message.error(res.data.msg);
            }
          });
        }
      });
    },
    // 详情
    getDetail() {
      this.$http({
        method: "get",
        url: "/manage/api/bus/customer/get_by_id",
        params: {
          customerId: this.$route.query.id
        }
      }).then(res => {
        if (res.data.code === 0) {
          
          if (this.pageAction === "edit") {
            let {
              id,
              customerName,
              customerType,
              customerRole,
              customerContact
            } = res.data.data;
            this.pageData = {
              id,
              customerName,
              customerType,
              customerRole,
              customerContact
            };
          } else {
            this.pageData = res.data.data;
          }
        }
      });
    },
    // 客户联系方式
    addCustomerContact() {
      if (this.pageData.customerContact.length >= 20) {
        this.$message.warning("最多可添加20个联系方式！");
      } else {
        this.pageData.customerContact.push({
          principal: "",
          contact: "",
          address: ""
        });
      }
    },
    removeCustomerContact(index) {
      this.pageData.customerContact.splice(index, 1);
    }
  },
  created() {
    this.fetchCustomerOptions();
    if (["edit", "detail"].includes(this.pageAction)) {
      this.getDetail();
    }
  }
};
</script>